package org.tinygroup.parsedsql.visitor;

import org.tinygroup.commons.tools.StringUtil;
import org.tinygroup.context.Context;
import org.tinygroup.parsedsql.SQLBuilder;
import org.tinygroup.parsedsql.base.DatabaseType;
import org.tinygroup.parsedsql.parser.SQLVisitor;
import org.tinygroup.parsedsql.util.SQLUtil;

import com.alibaba.druid.sql.ast.SQLExpr;
import com.alibaba.druid.sql.ast.expr.SQLBinaryOpExpr;
import com.alibaba.druid.sql.ast.expr.SQLVariantRefExpr;
import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlOutputVisitor;

/**
 * 
 * @author ballackhui
 *
 */
public  abstract class AbstractMySQLVisitor extends MySqlOutputVisitor implements
		SQLVisitor {

	private Context context;
	
	public AbstractMySQLVisitor() {
		super(new SQLBuilder());
		setPrettyFormat(false);
	}
	
	
	@Override
	public final DatabaseType getDatabaseType() {
		return DatabaseType.MySQL;
	}


	@Override
	public final SQLBuilder getSQLBuilder() {
		return (SQLBuilder) appender;
	}

	@Override
	public final void printToken(final String token) {
		getSQLBuilder().appendToken(SQLUtil.getExactlyValue(token));
	}

	@Override
	public final void printToken(final String label, final String token) {
		getSQLBuilder().appendToken(label, SQLUtil.getExactlyValue(token));
	}

	/**
	 * 父类使用<tt>@@</tt>代替<tt>?</tt>,此处直接输出参数占位符<tt>?</tt>
	 * 
	 * @param x
	 *            变量表达式
	 * @return false 终止遍历AST
	 */
	@Override
	public final boolean visit(final SQLVariantRefExpr x) {
		print(x.getName());
		return false;
	}
	
	@Override
	public boolean visit(final SQLBinaryOpExpr x) {
		SQLExpr right = x.getRight();
		SQLExpr left=x.getLeft();
		SQLVariantRefExpr refExpr=null;
		if(right instanceof SQLVariantRefExpr){
			refExpr=(SQLVariantRefExpr)right;
		}else if(left instanceof SQLVariantRefExpr){
			refExpr=(SQLVariantRefExpr)left;
		}
		if(refExpr!=null){
			String refName=refExpr.getName();
			Object paramValue = getContext().get(StringUtil.substringAfter(refName, "@"));
			if(paramValue==null){
			     print(" 1=1 ");	
			     return false;
			}
		}
		/*if(right instanceof SQLCharExpr){
			SQLCharExpr charExpr=(SQLCharExpr)right;
			String text = charExpr.getText();
			int startIndex=0;
			int endIndex=text.length();
			if(text.startsWith("_")||text.startsWith("%")){
				startIndex=1;
			}
			if(text.endsWith("_")||text.endsWith("%")){
				endIndex=text.length()-1;
			}
			String replaceText=text.substring(startIndex, endIndex);
			Object paramValue = getContext().get(StringUtil.substringAfter(replaceText, "@"));
			if(paramValue==null){
			     print(" 1=1 ");	
			     return false;
			}
		}*/
		return super.visit(x);
	}

	@Override
	public Context getContext() {
		return context;
	}

	@Override
	public void setContext(Context context) {
		this.context=context;
	}
}
